package entity

import (
	"QImages/database"
	"github.com/jinzhu/gorm"
)

// Image 图片，与数据库中images表相对应
type Image struct {
	gorm.Model
	Url      string
	Desc     string
	Title    string
	Label    string
	Likes    int64
	Comments []Comment `gorm:"ForeignKey:ImageID;AssociationForeignKey:ID"`
	UserID   uint
}

func init() {
	database.DB.Set("gorm:table_options", "ENGINE=InnoDB CHARSET=utf8mb4").AutoMigrate(&Image{})
}

// defaultPageSize 默认分页大小
var defaultPageSize = 12

// Insert 添加图片信息
func (image Image) Insert() (id uint, err error) {
	result := database.DB.Create(&image)
	id = image.ID
	if result.Error != nil {
		err = result.Error
		return
	}
	return
}

// PageImages 分页查询图片信息
func PageImages(pageNum, pageSize int) (images []Image, err error) {
	if pageSize == 0 {
		pageSize = defaultPageSize
	}
	offset := pageSize * (pageNum - 1)
	if err = database.DB.Offset(offset).Limit(pageSize).Preload("Comments").Find(&images).Error; err != nil {
		return
	}
	return
}

// FindImageById 根据图片id查询图片信息
func FindImageById(id uint) (image Image, err error) {
	if err = database.DB.Where("id = ?", id).Preload("Comments").Find(&image).Error; err != nil {
		return
	}
	return
}

// Update 更新图片信息
func (image *Image) Update(id uint) (updateImage Image, err error) {
	if err = database.DB.First(&updateImage, id).Error; err != nil {
		return
	}
	//参数1:是要修改的数据
	//参数2:是修改的数据
	if err = database.DB.Model(&updateImage).Updates(&image).Error; err != nil {
		return
	}
	return
}

// DeleteImage 删除图片信息
func DeleteImage(id uint) (res Image, err error) {
	res.ID = id
	if err = database.DB.Delete(&res).Error; err != nil {
		return
	}
	if err = database.DB.Where("image_id = ?", id).Delete(Comment{}).Error; err != nil {
		return
	}
	if err = database.DB.Where("image_id = ?", id).Delete(Collection{}).Error; err != nil {
		return
	}
	return
}

// TimelineItem 时间线数据
type TimelineItem struct {
	Images []Image
	Date   string
}

// Timeline 获取时间线信息
func Timeline(uid uint) (timeline []TimelineItem, err error) {
	db := database.DB
	var times []string
	rows, err := db.Table("images").Select("distinct date_format(created_at, '%Y/%m')").Where("user_id = ? and deleted_at is null", uid).Rows()
	if err != nil {
		return
	}
	for rows.Next() {
		var str string
		err = rows.Scan(&str)
		if err != nil {
			return
		}
		times = append(times, str)
	}
	for _, item := range times {
		var images []Image
		db.Where("date_format(created_at, '%Y/%m') = ? and user_id = ?", item, uid).Find(&images)
		ti := TimelineItem{
			Date:   item,
			Images: images,
		}
		timeline = append(timeline, ti)
	}
	return
}
